#define  _CRT_SECURE_NO_WARNINGS
#include <queue>
#include <vector>
using namespace std;

class Solution {
public:
    int num1 = 0;
    int m, n;
    int dx[4] = { 1, -1, 0, 0 };
    int dy[4] = { 0, 0, 1, -1 };
    queue<pair<int, int>> q;
    int rotApple(vector<vector<int> >& grid) {
        // write code here
        m = grid.size(), n = grid[0].size();
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (grid[i][j] == 1) num1++;
                if (grid[i][j] == 2) q.push({ i, j });
            }
        }
        vector<vector<bool>> visited(m, vector<bool>(n, false));
        int ret = 0;
        while (!q.empty() && num1)
        {
            int tmp = q.size();
            ret++;
            while (tmp--)
            {
                queue<pair<int, int>> front;
                front.push(q.front());
                q.pop();
                for (int k = 0; k < 4; k++)
                {
                    int x = front.front().first + dx[k];
                    int y = front.front().second + dy[k];
                    if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1 && visited[x][y] == false)
                    {
                        num1--;
                        visited[x][y] = true;
                        q.push({ x, y });
                    }
                }
            }
        }
        return num1 == 0 ? ret : -1;
    }
};